package com.zy.explore.license.infrastructure.util.mock;

import lombok.extern.log4j.Log4j2;
import org.springframework.lang.Nullable;
import uk.co.jemos.podam.api.AttributeMetadata;
import uk.co.jemos.podam.api.DataProviderStrategy;
import uk.co.jemos.podam.api.PodamUtils;
import uk.co.jemos.podam.typeManufacturers.AbstractTypeManufacturer;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * description 随机字符串提供器
 * 根据注解 {@link MockProperty} 或者关键字提供随机字符串
 *
 * @author 🇨🇳中国印🇨🇳
 * @date 2022年04月17日 01:33:12
 * @since 1.0.0
 * @see FakerNameResolver
 * @see KeywordResolver
 */
@Log4j2
public class FakerStringManufacturer extends AbstractTypeManufacturer<String> {

    @Override
    public String getType(DataProviderStrategy strategy, AttributeMetadata metadata, Map<String, Type> map) {

        String result = resolveByAnnotation(metadata);
        if (result != null) {
            return result;
        }

        result = resolveByKeyword(metadata);
        if (result != null) {
            return result;
        }

        return defaultRandomString();
    }

    @Nullable
    private String resolveByKeyword(AttributeMetadata metadata) {
        String attributeName = metadata.getAttributeName();
        if (attributeName == null) {
            return null;
        }
        try {
            return KeywordResolver.resolve(attributeName);
        } catch (ResolveNotFoundException ex) {
            log.debug(ex.getMessage());
        }
        return null;
    }

    @Nullable
    private String resolveByAnnotation(AttributeMetadata metadata) {
        MockProperty property = this.findElementOfType(metadata.getAttributeAnnotations(), MockProperty.class);
        if (property == null) {
            return null;
        }

        if (!property.value().isEmpty()) {
            return property.value();
        }

        try {
            return FakerNameResolver.resolve(property.faker(), property.lang());
        } catch (ResolveNotFoundException ex) {
            log.debug(ex.getMessage());
        }
        return null;
    }

    private String defaultRandomString() {
        StringBuilder buff = new StringBuilder();
        int limit = 10;
        while (buff.length() < limit) {
            buff.append(PodamUtils.getNiceCharacter());
        }

        return buff.toString();
    }
}
